<template>
	<view class="box-rgba">
		<view class="detail-container">
			<!-- 真实姓名 -->
			<view class="form-item">
				<text class="label">真实姓名 *</text>
				<input class="value" v-model="formData.name" placeholder="请输入真实姓名" />
			</view>

			<!-- 身份证号 -->
			<view class="form-item">
				<text class="label">身份证号 *</text>
				<input class="value" v-model="formData.IDnumber" placeholder="请输入身份证号" />
			</view>

			<!-- 性别 (Picker 选择) -->
			<view class="form-item">
				<text class="label">性别 *</text>
				<view class="value picker-trigger" @click="showGenderPicker = true">
					{{ formData.gender || '请选择' }}
				</view>
				<u-picker :show="showGenderPicker" :columns="genderOptions" @confirm="handleGenderConfirm"
					@cancel="showGenderPicker = false"></u-picker>
			</view>

			<!-- 出生日期 (日期选择器) -->
			<view class="form-item">
				<text class="label">出生日期 *</text>
				<view class="value" @click="showBirthdayPicker = true">
					{{ formData.birthday || '请选择' }}
				</view>
				<u-datetime-picker :min-date="-2208988800000" :max-date="1767139200000" :show="showBirthdayPicker"
					mode="date" @confirm="handleBirthdayConfirm"
					@cancel="showBirthdayPicker = false"></u-datetime-picker>
			</view>

			<!-- 联系电话 -->
			<view class="form-item">
				<text class="label">联系电话 *</text>
				<input class="value" v-model="formData.phone" placeholder="请输入联系电话" />
			</view>

			<!-- 现居地 -->
			<view class="form-item">
				<text class="label">现居地</text>
				<input class="value" v-model="formData.address" placeholder="请输入现居地" />
			</view>

			<!-- 与本人关系 -->
			<view class="form-item">
				<text class="label">与本人关系</text>
				<view class="value picker-trigger" @click="showRelationPicker = true">
					{{ formData.relationship || '请选择' }}
				</view>
				<u-picker :show="showRelationPicker" :columns="relationOptions" @confirm="handleRelationConfirm"
					@cancel="showRelationPicker = false"></u-picker>
			</view>


			<!-- 设为默认 -->
			<view class="form-item">
				<text class="label">设为默认</text>
				<u-switch v-model="formData.isDefault" />
			</view>

			<!-- 健康档案（跳转按钮） -->
			<view class="form-item health-record" @click="gotoHealthRecord">
				<text class="label">健康档案</text>
				<text class="value">查看</text>
			</view>

			<!-- 操作按钮（删除 + 保存） -->
			<view class="button-group">
				<button class="delete-btn" @click="deleteMember">删除家庭成员</button>
				<button class="save-btn" @click="saveMember">保存</button>
			</view>
		</view>
	</view>

</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		reactive
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		useUserStore
	} from '../../../store/user';

	// 表单数据（双向绑定）
	const formData = ref({
		name: '', // 真实姓名
		IDnumber: '', // 身份证号
		gender: '', // 性别：男/女
		birthday: '', // 出生日期
		phone: '', // 联系电话
		address: '', // 现居地
		relationship: '', // 与本人关系
		isDefault: false // 是否设为默认
	});

	// 选择器配置
	const genderOptions = reactive([
		['男', '女']
	]); // 性别选项
	const relationOptions = reactive([
		['本人', '父亲', '母亲', '子女']
	]); // 关系选项
	const showGenderPicker = ref(false); // 性别选择器显隐
	const showBirthdayPicker = ref(false); // 日期选择器显隐
	const showRelationPicker = ref(false); // 关系选择器显隐


	// 接收页面传参并初始化表单
	onLoad((options) => {
		if (options.item) {
			try {
				const item = JSON.parse(decodeURIComponent(options.item));
				formData.value = {
					...item.otherId,
					_id: item.otherId._id,
					relationship: item.relationship,
					isDefault: item.otherId.isDefault == 1,
					gender: item.otherId.gender == 1 ? '男' : '女',
					birthday: item.otherId.birthday
				};
			} catch (e) {
				console.error('解析参数失败:', e);
			}
		}
	});


	// 处理性别选择确认
	const handleGenderConfirm = (val) => {
		formData.value.gender = val.value[0]; //拿到男或女
		showGenderPicker.value = false;
	};

	// 处理选则日期
	const handleBirthdayConfirm = (val) => {
		console.log('日期对象', val);
		// 1. 将时间戳转为 Date 对象  
		const date = new Date(val.value);
		// 2. 提取年、月、日（月需 +1，因为月份从 0 开始）  
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零，如 1→"01"  
		const day = String(date.getDate()).padStart(2, '0'); // 补零，如 5→"05"  
		// 3. 拼接为 YYYY-MM-DD 格式  
		const formattedBirthday = `${year}-${month}-${day}`;
		// 4. 赋值给表单  
		formData.value.birthday = formattedBirthday;
		showBirthdayPicker.value = false;
	};

	// 处理关系选择确认
	const handleRelationConfirm = (val) => {
		formData.value.relationship = val.value[0]; //拿到关系名称
		showRelationPicker.value = false;
	};

	// 跳转健康档案页面（携带 _id 参数）
	const gotoHealthRecord = () => {
		if (!formData.value._id) {
			uni.showToast({
				title: '居民ID不存在',
				icon: 'none'
			});
			return;
		}

		uni.navigateTo({
			url: `/HealthHeadlinesPackage/pages/HealthRecord/HealthRecord?_id=${formData.value._id}`
		});
	};
	const userStore = useUserStore()
	// 删除家庭成员（二次确认）
	const deleteMember = () => {
		uni.showModal({
			title: '确认删除',
			content: '是否确定删除该家庭成员？删除后不可恢复',
			success: (res) => {
				if (res.confirm) {
					uni.request({
						url: 'http://nocat.life:3012/relations/removeFamily',
						method: 'DELETE',
						data: {
							ownId: userStore.userInfo._id, // 当前登录用户 ID
							otherId: formData.value._id, // 待删除成员 ID						
						},
						// 接口成功响应处理
						success: (response) => {
							const {
								code,
								msg
							} = response.data;
							if (code === 200) {
								uni.showToast({
									title: '删除成功'
								});
								uni.navigateBack(); // 返回上一页

							} else {
								uni.showToast({
									title: msg || '删除失败，请稍后重试',
									icon: 'none'
								});
							}
						},
						//  网络/请求失败处理
						fail: (err) => {
							uni.showToast({
								title: '网络异常，删除失败',
								icon: 'none'
							});
							console.error('删除家庭成员接口异常：', err); // 调试用
						}
					});
				}
			}
		});
	};

	// 保存表单数据
	const saveMember = () => {
		// 表单验证
		if (!formData.value.name) {
			uni.showToast({
				title: '请输入真实姓名',
				icon: 'none'
			});
			return;
		}

		// 格式转换（适配后端接口）
		const submitData = {
			...formData.value,
			isDefault: formData.value.isDefault ? 1 : 0, // Switch 转 1/0
			gender: formData.value.gender === '男' ? 1 : 0 // 性别转 1/0
		};

		// TODO：替换为真实后端接口
		uni.showToast({
			title: '保存成功'
		});
		uni.navigateBack();
	};
</script>

<style lang="scss" scoped>
	.box-rgba {
		min-height: 100vh;
		background-color: rgba(242, 247, 251, 0.619607843137255);
	}

	.detail-container {
		padding: 0;
		background-color: #fff;
	}

	.form-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 30rpx;
		border-bottom: 1px solid #F5F5F5;
	}

	.label {
		font-size: 28rpx;
		color: #333;
		width: 140rpx;
	}

	.value {
		font-size: 28rpx;
		color: #666;
		flex: 1;
		margin-left: 20rpx;
		cursor: pointer;
	}

	/* 【新增】Picker 统一箭头样式 */
	.picker-trigger {
		position: relative;
		padding-right: 40rpx;
		/* 预留箭头空间，避免文字被遮挡 */
	}

	.picker-trigger::after {
		content: "";
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 18rpx;
		height: 28rpx;
		background: url('/static/icons/jiantou.png') no-repeat center;
		/* 箭头图标路径，需确保存在 */
		background-size: contain;
	}

	/* 输入框样式 */
	input {
		flex: 1;
		height: auto;
		padding: 0;
		border: none;
		background: transparent;
		color: #666;
		font-size: 28rpx;
	}

	input::placeholder {
		color: #999;
		font-size: 28rpx;
	}

	/* 健康档案（若也需箭头，可复用 picker-trigger，否则保留原有样式） */
	.health-record {
		justify-content: space-between;
	}

	.health-record .value {
		color: #007aff;
		// text-decoration: underline;
		position: relative;
		padding-right: 40rpx;
	}

	.health-record .value::after {
		content: "";
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 18rpx;
		height: 28rpx;
		background: url('/static/icons/jiantou.png') no-repeat center;
		background-size: contain;
	}

	/* 开关位置 */
	.form-item .u-switch {
		margin-left: auto;
	}

	/* 保留原有按钮样式 */
	.button-group {
		display: flex;
		justify-content: space-around;
		margin: 40rpx 20rpx;
	}

	.delete-btn,
	.save-btn {
		width: 300rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 10rpx;
		font-size: 28rpx;
	}

	.delete-btn {
		background-color: #fff;
		color: #f00;
		border: 1px solid #f00;
	}

	.save-btn {
		background-color: #007aff;
		color: #fff;
		border: none;
	}
</style>